import React, { Component } from 'react';
import { Modal, Form, Input } from 'antd';
import SelectSeach from '../Form/Select/SelectSeach';


const FormItem = Form.Item;

class UserEditModal extends Component {

  constructor(props) {
    super(props);
    this.state = {
      visible: false,
    };
  }

  showModelHandler = (e) => {
    if (e) e.stopPropagation();
    this.setState({
      visible: true,
    });
  };

  hideModelHandler = () => {
    this.setState({
      visible: false,
    });
  };

  okHandler = () => {
    const { onOk } = this.props;
    this.props.form.validateFields((err, values) => {
      if (!err) {
        onOk(values);
        this.hideModelHandler();
      }
    });
  };

  
  render() {
    const config=this.props.config;

    const { children } = this.props;
    const { getFieldDecorator } = this.props.form;
    const initData= this.props.record;;
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
    };   
     const { formLayout } = this.state;
   
 
    const rs=config.map(item=>{

    let itemRender=function(){
      return (<Input />);
      //return (<SelectSeach dataSourceURL='musicSinger/get' />);
    }
    if(item.hasOwnProperty("render")){
      itemRender=item.render;
    }
    let fieldDec={}
    if(item.isInit){
       fieldDec.initialValue=getVlue(item.key,initData);
    }
    if(item.hasOwnProperty("rules")){     
      fieldDec.rules=item.rules;       
    }
    
    
    return (<FormItem
                  {...formItemLayout}
                  label={item.key}
                >
                  {
                    getFieldDecorator(item.key,fieldDec)(itemRender())
                  }
            </FormItem>)      

  })
 
  
    return (
      <span>
        <span onClick={this.showModelHandler}>
          { children }
        </span>
        <Modal
          title="编辑"
          visible={this.state.visible}
          onOk={this.okHandler}
          onCancel={this.hideModelHandler}
        >
          <Form layout={formLayout} onSubmit={this.okHandler}>
           {rs}
          </Form>
        </Modal>
      </span>
    );
  }
}



function getVlue(attr,dataSource){ 
    let value=dataSource;
    while(true){
      let curAttr=attr.substring(0,attr.indexOf("."));
      if(attr.indexOf(".")==-1){
        curAttr=attr;
      }else{
        curAttr=attr.substring(0,attr.indexOf("."));
      }         
      value=value[curAttr];     
      
      if(attr.indexOf(".")==-1){
        break;
      }
      attr=attr.substring(attr.indexOf(".")+1);      
    }
    return value;
}

export default Form.create()(UserEditModal);